﻿/*********************************************************
 * copyright learnren.com 版权所有
 * 开发人员：minyuan
 * 创建时间：2015/11/3 5:20:51
 * 描述说明：
 *
 * 更改历史：
 *
 ********************************************************/

using Newtonsoft.Json;
using System;
using System.Net;
using System.Web;

namespace NQQOpenApi
{
    /// <summary>
    /// PC网站接入API管理类
    /// </summary>
    public class PCApiManager
    {
        public PCApiManager()
        {

        }

        public PCApiManager(string appId, string appKey)
        {
            this.AppId = appId;
            this.AppKey = appKey;
        }

        /// <summary>
        /// 从http://connect.qq.com申请到的appid
        /// </summary>
        public string AppId { get; set; }

        /// <summary>
        /// 从http://connect.qq.com申请到的appkey
        /// </summary>
        public string AppKey { get; set; }

        /// <summary>
        /// 获取QQ登录窗口地址
        /// </summary>
        /// <param name="redirectUrl">成功授权后的回调地址，必须是注册appid时填写的主域名下的地址，
        /// 建议设置为网站首页或网站的用户中心。方法内部自动对此参数进行url编码。</param>
        /// <param name="state">client端的状态值。用于第三方应用防止CSRF攻击，
        /// 成功授权后回调时会原样带回。请务必严格按照流程检查用户与state参数状态的绑定。</param>
        /// <returns></returns>
        public string GetLoginUrl(string redirectUrl, string state, string scope = null, string display = null)
        {
            if (string.IsNullOrEmpty(redirectUrl))
            {
                throw new System.ArgumentException("redirectUrl不能为空或空字符串");
            }

            if (string.IsNullOrEmpty(state))
            {
                throw new System.ArgumentException("state不能为空或空字符串");
            }

            string result = string.Format("{0}?response_type=code&client_id={1}&redirect_uri={2}&state={3}",
                ApiUrls.PC_GETAUTHORIZECODE,
                AppId,
                HttpUtility.UrlEncode(redirectUrl),
                state);
            if (!string.IsNullOrEmpty(scope))
            {
                result += string.Format("&scope={0}", scope);
            }
            if (!string.IsNullOrEmpty(display))
            {
                result += string.Format("&display={0}", display);
            }
            return result;
        }

        /// <summary>
        /// 获取Access Token
        /// </summary>
        /// <param name="code">服务端返回到回调地址的authorization code</param>
        /// <param name="redirectUrl">与GetLoginUrl中传入的redirect_uri保持一致。</param>
        /// <returns></returns>
        public PCAccessToken GetAccessToken(string code, string redirectUrl)
        {
            string url = string.Format("{0}?grant_type=authorization_code&client_id={1}&client_secret={2}&code={3}&redirect_uri={4}",
                        ApiUrls.PC_GETTOKEN,
                        AppId,
                        AppKey,
                        code,
                        HttpUtility.UrlEncode(redirectUrl));
            string response = null;
            using (WebClient wc = new WebClient())
            {
                try
                {
                    response = wc.DownloadString(url);
                }
                catch
                {
                    throw;
                }
            }

            if (string.IsNullOrEmpty(response))
            {
                return new PCAccessToken
                {
                    Error = new ErrorMessage
                    {
                        ErrorCode = "-1",
                        ErrorDescription = "发生意外错误。QQ服务器返回结果为空。"
                    }
                };
            }

            // 截取返回结果中json
            response = response.Substring(response.IndexOf("{"));
            response = response.Substring(0, response.LastIndexOf("}") + 1);

            PCAccessToken result = null;

            try
            {
                result = JsonConvert.DeserializeObject<PCAccessToken>(response);
            }
            catch { }

            if (result == null)
                result = new PCAccessToken();

            if (string.IsNullOrEmpty(result.AccessToken))
            {
                try
                {
                    result.Error = JsonConvert.DeserializeObject<ErrorMessage>(response);
                }
                catch (Exception ex)
                {
                    result.Error = new ErrorMessage { ErrorCode = "-1", ErrorDescription = "发生意外错误。" + ex };
                }
                return result;
            }

            result.Error = new ErrorMessage { ErrorCode = "0", ErrorDescription = "OK" };

            return result;
        }



    }
}
